package com.xiaoq.matrix.activity.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.matrix.activity.entity.ActivityAttendentEntity;
import com.xiaoq.matrix.activity.repository.IActivityAttendRepository;
import com.xiaoq.vo.PagingVo;

@Repository
public class ActivityAttendRepositoryImpl implements IActivityAttendRepository{

	@Autowired
	private Datastore dataStore;
	
	@Autowired
	private IdGenerator idGenerator;
	
	private static final Logger LOG = LoggerFactory.getLogger(ActivityAttendRepositoryImpl.class);
	@Override
	public List<ActivityAttendentEntity> findActivityAttendByAct(String activityId) {
		if(StringUtils.isNotEmpty(activityId)){
			Query<ActivityAttendentEntity> activityAttendQuery = dataStore.find(ActivityAttendentEntity.class);
			activityAttendQuery.field("activityId").equal(activityId);
			List<ActivityAttendentEntity> activityAttendList = null;
			activityAttendList = activityAttendQuery.asList();
			return activityAttendList;
				
		}
		return null;
	}

	@Override
	public List<ActivityAttendentEntity> findActivityAttendByUser(String userId ,PagingVo pvo) {
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;
		List<ActivityAttendentEntity> activityAttendList = null;
		Query<ActivityAttendentEntity> activityAttendQuery = dataStore.find(ActivityAttendentEntity.class);
		Long total = 0L;
		if(StringUtils.isNotEmpty(userId)){
			activityAttendQuery.field("userId").equal(userId);
			total = activityAttendQuery.count();
			pvo.setTc(total);
			activityAttendQuery.order("-enrollTime").offset(pn).limit(ps);
			activityAttendList = activityAttendQuery.asList();
		}
		
		
		return activityAttendList;
	}

	@Override
	public boolean addActivityAttend(ActivityAttendentEntity activityAttend) {

		if(activityAttend!=null){
			activityAttend.setId(idGenerator.nextId());
			activityAttend.setEnrollTime(System.currentTimeMillis());
			dataStore.save(activityAttend);
			return true;
			
		}else{
			LOG.error("ActivityAttendentEntity 传递结果为空！");
		}
		return false;
	}

	@Override
	public boolean isUserAttend(String userId, String activityId) {
		Query<ActivityAttendentEntity> userAttendQuery = dataStore.createQuery(ActivityAttendentEntity.class);
		if(StringUtils.isNotEmpty(userId)&&StringUtils.isNoneEmpty(activityId)){
			userAttendQuery.field("userId").equal(userId).field("activityId").equal(activityId);
			ActivityAttendentEntity activityAttend = userAttendQuery.get();
			if(activityAttend!=null){
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

}
